package com.musicdaze;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

import com.musicdaze.graphics.MusicDazeUI;
import com.musicdaze.utils.schedule.TaskScheduler;

/**
 * The entry point for the MusicDaze application.
 * @author mfujihara
 *
 */
public class MusicDaze {
	/** scheduler */
	private static TaskScheduler scheduler;
	static{
		scheduler = new TaskScheduler();
	}
	/**
	 * application start
	 * @param args ignored
	 */
	public static void main(String[] args){
		MusicDaze md = new MusicDaze();
		if (md.checklock()){
			// good to go
			md.setup();
		}
	}
	/**
	 * Gets the scheduler
	 * @return
	 */
	public static TaskScheduler getScheduler() {
		return scheduler;
	}
	/**
	 * constructor
	 */
	private MusicDaze(){}
	/**
	 * Setup for the MusicDaze
	 */
	private void setup(){
		// itunes
		MusicDazeUI.getSplash().showSplash();
		setupItunes();
		MusicDazeUI.getSplash().closeSplash();
		//MusicDazeUI.getFrame().setVisible(true);
	}

	/**
	 * Initializes the itunes instance
	 */
	private void setupItunes() {
		ItunesController.getInstance();
	}
	/**
	 * Creates a lock for this application so only
	 * one instance can be running. Then on exit of application,
	 * it deletes the file and lock.
	 * @return true if lock was acquired, false otherwise.
	 */
	private boolean checklock(){
		try{
			final File f = new File("musicdaze.lock");
			if (f.exists()){
				f.delete();
			}
			final FileChannel ch = new RandomAccessFile(f, "rw").getChannel();
			final FileLock lock = ch.tryLock();
			if (lock==null){
				ch.close();
				return false;
			}
			Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						lock.release();
						ch.close();
						f.delete();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}));
			return true;
		}
		catch (IOException io){
			io.printStackTrace();
			return false;
		}
	}
}
